<?php
namespace Api\Controller;


use Api\Service\AddressService;
use Api\Service\CartService;
use Api\Service\GoodsService;
use Api\Service\LogService;
use Api\Service\OrderService;
use Api\Service\UserService;
use Mobile\Controller\OrdercallbackController;
use Think\Exception;

class OrderController extends LoginBaseController
{
    protected static $order_status_all='all';//所有订单
    protected static $order_status_waiting_pay='waiting_pay';//待支付订单
    protected static $order_status_waiting_delivery_goods='waiting_delivery';//待发货订单
    protected static $order_status_waiting_delivery='waiting_collect';//待收货订单
    protected static $order_status_over='over';
    protected $status_array;//array($this->order_status_all,'waiting_pay','waiting_delivery');
    public function __construct()
    {
        parent::__construct();
        $this->status_array=array(self::$order_status_all,self::$order_status_waiting_pay,self::$order_status_waiting_delivery);
    }

    //查询用户订单列表
    public function orderList(){
        $page=I('post.page');
        if(empty($page) || $page<1){
            $page=1;
        }
        $pageNum=I('post.page_num');
        if(empty($pageNum)|| $pageNum<10){
            $pageNum=10;
        }
        $where['uid']=$this->uid;
        $status=I('post.status');
        //dump($status);die;
        //LogService::S()->writeLog('log','orderList',$_POST);
        switch ($status){
            case self::$order_status_all:
                break;
            case self::$order_status_waiting_pay:
                $where['checked']=0;
                break;
            case self::$order_status_waiting_delivery_goods:
                $where['checked']=1;//array(array('EQ',1),array('EQ',5),'OR');
                break;
            case self::$order_status_over:
                $where['checked']=2;
                break;
            case self::$order_status_waiting_delivery:
                $where['checked']=5;
                break;
        }
        //dump($where);die;
        $pageCount=ceil(OrderService::S()->queryCountOrderByWhere($where)/$pageNum);//总页数
        //dump($pageCount);die;
        $orderList=OrderService::S()->queryOrderList($where,$page,$pageNum);
        foreach ($orderList as $k=>$v){
            $orderList[$k]['goods']=unserialize($orderList[$k]['goods']);
            foreach ($orderList[$k]['goods'] as $gk=>$gv){
                $orderList[$k]['goods'][$gk]['goods_pic']=C('UPYUN_DOMAIN').$gv['goods_pic'];
            }
        }
        //$data['list']=$orderList;
        //$data['pageCount']=$pageCount;//总页数
        $this->ajaxReturn(array('code'=>200,'msg'=>'success','data'=>$orderList,'pageCount'=>$pageCount));
        //$this->ajax(200,'success',$data);

    }

    //查询订单详细信息
    public function findOrderDetail(){
        $order_id=I('post.order_id');
        if(empty($order_id)){
            $this->ajax(202,'order_id不能为空');
        }
        $orderDetail=OrderService::S()->findOrderDetail($order_id);
        $goodsInfo=unserialize($orderDetail['goods']);
        $goods=array();
        foreach ($goodsInfo as $k=>$v){
            //$goodsInfo['shop_price']=$goodsInfo["grade{$this->member['grade_id']}_price"];
            $goods[$k]['goods_pic']=C('UPYUN_DOMAIN').$goodsInfo[$k]['goods_pic'];//$goodsInfo["grade{$this->member['grade_id']}_price"];
            $goods[$k]['num']=$v['num'];
            $goods[$k]['goods_name']=$v['goods_name'];
            $goods[$k]['shop_price']=$v['shop_price'];
        }
        $orderDetail['delivery']=unserialize($orderDetail['delivery']);
        $orderDetail['delivery']=$orderDetail['delivery']['address'];
        $orderDetail['goods']=$goods;
        //$this->ajaxReturn($goods);
        //dump($orderDetail);die;
        if(!$orderDetail){
            $this->ajax(202,'订单不存在');
        }
        $this->ajax(200,'success',$orderDetail);
    }

    //订单状态
    public function orderStatusCount(){
        $where['uid']=$this->uid;
        $data['all']=OrderService::S()->queryCountOrderByWhere($where);
        $where['checked']=0;
        $data['pending_payment']=OrderService::S()->queryCountOrderByWhere($where);
        $where['checked']=array(array('EQ',1),array('EQ',5),"OR");
        $data['pending_delivery']=OrderService::S()->queryCountOrderByWhere($where);
        $this->ajax(200,'success',$data);
    }


    //添加订单
    public function addOrder(){
        //重新遍历商品信息
        //$goodInfo=I('post.goodsInfo');;//'[{"goods_num":1,"goods_id":1}]';//I('post.goodsInfo');
        /*if(!is_array($goodInfo)){
            //$this->ajaxReturn($goodInfo);
            $goodInfo=json_decode($goodInfo,true);//json_decode($goodInfo,true);
            //dump($goodInfo);die;
        }*/
        $goods['goods_id']=I('post.goods_id');
        $goods['goods_num']=I('post.goods_num');
        $goodInfo[]=$goods;
        if(empty($goodInfo)){
            $this->ajax(202,'商品信息错误');
        }
        $result=self::createOrder($goodInfo);
        if($result){
           $this->ajax(200,'success',$result);
        }else{
            $this->ajax(202,'error');
        }
    }

    //购物车下单
    public function addOrderByCart(){
        $cart_ids=I('post.cart_ids');
        $cart_where = array(
            "uid" => $this->uid,
            "cart_id" => array(
                "IN",$cart_ids
            )
        );
        //dump($cart_where);die;
        //查询出购物车的商品信息
        $cartInfo=CartService::S()->queryCartByWhere($cart_where);
        //dump($cartInfo);die;
        if(!$cartInfo){
            $this->ajax(202,'购物车信息错误');
        }
        //删除购物车商品
        $goodsArray=array();
        foreach ($cartInfo as $k=>$v) {
            $goods['goods_id']=$v['goods_id'];
            $goods['goods_num']=$v['goods_num'];
            $goodsArray[]=$goods;
        }
        $result=self::createOrder($goodsArray);
        if($result){
            CartService::S()->delCartByWhere($cart_where);//删除购物车信息
            $this->ajax(200,'success',$result);
        }else{
            $this->ajax(202,'error');
        }
    }

    /**
     * 创建订单
     * @param $goodInfo
     * @param null $cart_ids
     * @return bool
     */
    public function createOrder($goodInfo,$grade_id=null){
        $addGoods=array();
        //$goodsFiled=GoodsService::S()->goodsFiled().",grade{$this->member['grade_id']}_price";,$goodsFiled
        $orderPrice=0;
        $goods_ids='';
        $goods_names='';
        $goods_sale='';
        //$goodInfo[]=array('goods_id'=>1,'goods_num'=>1);
        foreach ($goodInfo as $k=>$v){
            //查询出商品数量是否足够
            $goods=GoodsService::S()->findGoodsInfoByGoodsId($v['goods_id']);
            if($v['goods_num']<1){
                $v['goods_num']=1;
            }
            if($goods['stock']<=$v['goods_num']){//库存小于商品
                LogService::S()->writeLog('createOrderError','商户库存不足',$_POST);
                $this->ajax(202,'库存不足');
            }
            $goods['shop_price']=$goods["grade{$this->member['grade_id']}_price"];
            $orderPrice+=$goods['shop_price']*$v['goods_num'];//计算订单金额
            $goods['num']=$v['goods_num'];
            $goods_ids.=$v['goods_id'].",";
            $goods_names.=$goods['goods_name'].",";
            $goods_sale.="{$v['goods_id']},{$v['goods_num']};";
            $addGoods[]=$goods;
        }
        $goods_ids=substr($goods_ids,0,-1);
        $orderPrice=round($orderPrice,2);
        //开店等级计算金额

        if($grade_id==3){
            $orderPrice=200;
        }elseif($grade_id==4){
            $orderPrice=2000;
        }
        //dump($orderPrice);die;
        $address_id=I('post.address_id');
        if(empty($address_id)){
            $this->ajax(202,'收货地址不能为空');
        }
        $addressInfo=AddressService::S()->findAddByWhere(array('id'=>$address_id));
        $orderData=self::back_order_data($addGoods,$addressInfo,$orderPrice);
        //$this->ajax(200,'success',$orderData);
        $orderData['goods_names']=substr($goods_names,0,-1);
        $orderData['goods_sale']=substr($goods_sale,0,-1);
        if(!empty($grade_id)){
            $orderData['grade_id']=$grade_id;
        }
        $orderData['remark']=I('post.khnote');
        $orderData['goods_ids']=$goods_ids;//substr($goods_sale,0,-1);
        $orderData['order_type'] = 1;
        //dump($orderData);die;
        $order_id=OrderService::S()->addOrder($orderData);
        if($order_id){
            //扣除微币
            $order_data['order_id'] = $order_id;
            UserService::S()->_kou_score($order_data,$this->member);
            $ajaxdata['order_id']=$order_id;
            $ajaxdata['is_pay']=0;
            //判断还需不需要微信支付
            if($order_data['pay_money'] == 0 && ($order_data['pay_orgmoney']>0)){
                //不需要再次微信支付了
                //更改订单状态
                //$res = A("Ordercallback")->_changeOrder($order_data,2);//更改状态为已经支付
                $ordercallback = new OrdercallbackController();
                $res = $ordercallback->_changeOrder($order_data, 2);
                if(!$res){
                        return false;
                }else{
                    $ajaxdata['is_pay']=1;
                    return $ajaxdata;
                    //return_json(0,"订单支付成功","","/mobile/orderdetail?order_id=".$order_id."&showwxpaytitle=1");
                }
            }
            return $ajaxdata;
                //return_json(0,"订单已提交,正在转入支付页面...","","/mobile/orderdetail?order_id=".$order_id."&showwxpaytitle=1");
        }else{
           return false;
        }
    }

    //取消订单
    public function cancelOrder(){
        $order_id=I('post.order_id');
        $orderInfo=OrderService::S()->findOrderDetail($order_id);
        if(!$orderInfo){
            $this->ajax(202,'订单不存在');
        }else{

            if($orderInfo['create_time'] > date("Y-m-d H:i:s",time()-1*60)){
                $this->ajax(200,"为了你的账户安全,订单创建1分钟内不允许取消,请1分钟后重试");
            }

            if($orderInfo['uid']!=$this->uid){
                $this->ajax(202,'订单错误');
            }
            if($orderInfo['checked']!=0){
                $this->ajax(202,'订单状态不允许取消');
            }
            $close_reason=I('post.reason');//取消理由

            $data = array(
                "close_time" => date("Y-m-d H:i:s"),
                "checked" => 6,
                "is_closebysys" => 0,
                "close_reason" => $close_reason
            );
            $re=OrderService::S()->saveOrderInfo($order_id,$data);
            if($re){
                OrderService::S()->orderCancel($orderInfo['yongjin_money'],$orderInfo,1);//返佣金
                OrderService::S()->orderCancel($orderInfo['cash_money'],$orderInfo,3);//返现金
                OrderService::S()->orderCancel($orderInfo['score_money'],$orderInfo,2);//返重消币
                OrderService::S()->orderCancel($orderInfo['tihuo_money'],$orderInfo,11);//返提货币
                OrderService::S()->orderCancel($orderInfo['prize_money'],$orderInfo,12);//返提货币
                $this->ajax(200,'success');//修改成功
            }else{
                $this->ajax(202,'取消订单失败');
            }
        }
    }


    /**
     * 返回订单数据
     * @param $goods_info
     * @param $delivery_data
     * @param $goods_money
     * @param bool $order_grade
     * @return mixed
     */
    protected function back_order_data($goods_info,$delivery_data,$goods_money,$order_grade=false){
        $data['delivery_name'] = $delivery_data['name'];//收货人姓名
        $data['delivery_mobile'] = $delivery_data['mobile'];//收货人电话
        $data['bill_name'] = $delivery_data['bill_name'];
        $data['delivery'] = serialize($delivery_data);//收货的地址

        $data['province'] = $delivery_data['province'];
        $data['city'] = $delivery_data['city'];
        $data['county'] = $delivery_data['county'];

        $data['khnote'] = post('khnote');//客户留言
        $data['uid'] = $this->uid;
        //$data['openid'] = $this->member['openid'];
        $data['openid'] = $this->member['openid'];
        $data['nickname'] = $this->member['nickname'];
        $data['realname'] = $this->member['realname'];//下单人真实姓名

        $data['refer_uid'] = $this->member['refer_uid'];//我的上级uid
        $data['refer_nickname'] = $this->member['refer_nickname'];

        $data['order_sn'] = 'WX'.date("YmdHis").sprintf("%05d", $this->uid).rand(10,99);//生成订单号

        $data['checked'] = 0;//未支付
        $data['create_time'] = date("Y-m-d H:i:s");//创建时间

        $data['goods'] = serialize($goods_info);//把商品信息序列化
        $data['order_title'] = $goods_info[0]['goods_name'];//第一件商品的商品名称


        //$goods_money= round($money,2);
        $data['all_money'] =$goods_money ;//$money_arr['all_money'];
        $data['pay_orgmoney'] =$goods_money ;//round($goods_money,2);//订单原始总价(未使用任何优惠的价格)
        $data['order_type'] = isset($_POST['order_type'])?$_POST['order_type']:0;

        $data['shipping']=OrderService::S()->get_shipping($goods_info,$delivery_data['province_id']);//self::_get_shipping($goods_info,$delivery_data['province_id']);//计算运费
        $shipping = $data['shipping'];//运费
        //使用优惠券
        //TODO
        $coupon_money = 0;//TODO
        $data['coupon_money'] = 0;

        $goods_money -= $data['coupon_money'];//商品费用减去优惠券

        $use_score =  post('use_score');
        if($use_score==1 && ($goods_money>0 || $shipping>0) && $goods_info[0]['gtype_id']==9 && count($goods_info)==1){

            if($this->member['score']>=$goods_money){
                if($this->member['score']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['score_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    $data['score_money'] = $this->member['score'];//使用完
                    $shipping = $shipping-($this->member['score']-$goods_money);
                }
                $goods_money = 0;
            }else{
                //不够,部分使用佣金
                $data['score_money'] = $this->member['score'];//
                $goods_money -= $this->member['score'];
            }
        }

        $use_yongjin =  post('use_yongjin');//是否使用佣金
        //使用佣金
        if(($goods_money>0 || $shipping>0) && ($use_yongjin == 1)){

            if($this->member['money']>=$goods_money){
                //足够,全额使用佣金

                if($this->member['money']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['yongjin_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    $data['yongjin_money'] = $this->member['money'];//使用完
                    $shipping = $shipping-($this->member['money']-$goods_money);
                }

                $goods_money = 0;
            }else{
                //不够,部分使用佣金
                $data['yongjin_money'] = $this->member['money'];//
                $goods_money -= $this->member['money'];
            }
        }

        $use_prize =  post('use_prize');//是否使用佣金
        //使用奖励佣金
        if(($goods_money>0 || $shipping>0) && ($use_prize == 1)){

            if($this->member['prize_money']>=$goods_money){
                //足够,全额使用佣金

                if($this->member['prize_money']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['prize_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    $data['prize_money'] = $this->member['prize_money'];//使用完
                    $shipping = $shipping-($this->member['prize_money']-$goods_money);
                }

                $goods_money = 0;
            }else{
                //不够,部分使用佣金
                $data['prize_money'] = $this->member['prize_money'];//
                $goods_money -= $this->member['prize_money'];
            }
        }

        $use_cash =  post('use_cash');//是否使用充值币
        //使用余额
        if(($goods_money>0 || $shipping>0) && ($use_cash == 1)){

            if($this->member['cash_money']>=$goods_money){
                //足够,全额使用
                if($this->member['cash_money']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['cash_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费

                    $data['cash_money'] = $this->member['cash_money'];//使用完
                    $shipping = $shipping-($this->member['cash_money']-$goods_money);
                }

                $goods_money = 0;
            }else{
                //不够,部分使用
                $data['cash_money'] = $this->member['cash_money'];//
                $goods_money -= $this->member['cash_money'];
            }
        }

        $data['pay_nowmoney'] = $goods_money;//订单原始总价(使用优惠券,积分后的价格)
        $data['pay_money'] = $data['pay_nowmoney']+$shipping;//总的费用=优惠后的商品钱+运费
        $data['order_cashmoney'] = $this->_get_pay_cash($data,$goods_money);//除去折扣等后,订单中能够产生佣金的金额
        $data['zhekou_money'] = $goods_money+$data['shipping']-$data['pay_money']-$data['score_money']-$data['ex_cash']-$data['prize_money']-$data['cash_money'];

        if($data['pay_money']<0){
            return_json(1,"商品价格出错了");//可以等于0
        }
        $data['order_ip'] = get_client_ip();//订单ip
        $data['is_comment'] = 0;//未评论

        return $data;
    }

    /*
    * 订单中需要支付佣金的钱(扣除折扣)
    */
    protected function _get_pay_cash($order,$money=false){
        $goodslist = unserialize($order['goods']);
        if($money) {
            return $money;
        }
        $pay_cash = 0;
        foreach($goodslist as $v) {
            if($v['is_fx_commission']) {
                $pay_cash += $v['shop_price']*$v['num'];
            }
        }
        return $pay_cash ? $pay_cash : 0;

    }

    //根据订单状态查询出订单信息
    public function queryOrderByStatus(){
        $status=I('post.status');
        if(!in_array($status,$this->status_array)){
            $this->ajax(202,'订单状态错误');
        }
        $where['uid']=$this->uid;
        switch ($status){
            case self::$order_status_all:
                break;
            case self::$order_status_waiting_pay:
                $where['checked']=0;
                break;
            case self::$order_status_waiting_delivery:
                $where['checked']=array(array('EQ',1),array('EQ',5),'OR');
                break;
        }
        //dump($where);die;
        $orderList=OrderService::S()->queryOrderList($where);
        $this->ajax(200,'success',$orderList);
    }

    //用户提货操作
    public function tihuo(){
        $addWhere['uid']=$this->uid;
        $addWhere['id']=I('post.address_id');
        $delivery_data = AddressService::S()->findAddByWhere($addWhere);//$addressController->_get_delivery_data();
        if(empty($delivery_data)) {
            $this->ajax(202,'请选择收货地址');
        }
        $goodslist = I('post.goodsInfo');
        $goodslist=htmlspecialchars_decode($goodslist);
        $goodslist=json_decode($goodslist,true);
        if(!$goodslist) {
            $this->ajax(202,'请选择商品');
        }
        $addGoods = $order_data = array();
        $all = 0;
        $orderPrice=0;
        $goods_ids='';
        $goods_names='';
        $goods_sale='';
        foreach($goodslist as $v) {
            //查询出商品数量是否足够
            $goods=GoodsService::S()->findGoodsInfoByGoodsId($v['goods_id']);
            if($goods['stock']<$v['num']){//库存小于商品
                $this->ajax(202,'库存不足');
            }
            $goods['shop_price']=$goods["grade{$this->member['grade_id']}_price"];
            $orderPrice+=$goods['shop_price']*$v['num'];//计算订单金额
            $goods['num']=$v['num'];
            $goods_ids.=$v['goods_id'].",";
            $goods_names.=$goods['goods_name'].",";
            $goods_sale.="{$v['goods_id']},{$v['num']};";
            $addGoods[]=$goods;
        }
        $orderPrice=round($orderPrice,2);
        if(empty($addGoods)) {
            $this->ajax(202,'请选择商品');
        }
        if($orderPrice>$this->member['stock']) {
            $this->ajax(202,'你的库存不足，无法提货');
        }
        $order_data = self::back_order_data($addGoods,$delivery_data,$orderPrice);//$this->_get_order_data($goods_info,$delivery_data);
        $order_data['goods_ids'] = implode(',',$goods_ids);//商品id,多个用逗号分割
        $order_data['goods_names'] = implode(",",$goods_names);//订单所有商品名称和编号的综合，用于做查询
        $order_data['goods_sale'] = implode(";",$goods_sale);//id和销量组合，用作统计销量
        $order_data['order_type'] = 3;
        $order_data['checked'] = 1;
        $order_data['pay_nowmoney'] = 0;
        $order_data['pay_orgmoney'] = 0;
        $order_data['pay_money'] = 0;
        $order_data['order_cashmoney'] = 0;
        $order_data['pay_time'] = date('Y-m-d H:i:s');
        $order_id = OrderService::S()->addOrder($order_data);//$this->orderModel->add($order_data);
        if($order_id) {
            $order_data['order_id'] = $order_id;
            core_moneylog($order_data['uid'],-$all,4,'提货扣库存',$order_data);
            $this->ajax(200,'提货完成');
        }else{
            $this->ajax(202,'提货失败，请重试');
        }
    }

    public function test(){
        $d=I('dt');
        dump($d);
    }

    public  function clearbom($contents){
        //UTF8 去掉文本中的 bom头
        $BOM = chr(239).chr(187).chr(191);
        return str_replace($BOM,'',$contents);
    }

    public function daili_orderadd(){

        try{
            //$this->ajaxReturn($_POST);
            //$data=;//file_get_contents('php://input');
            //$_POST=json_decode('{"address_id":"1586","goods_info":"[{\"num\":1,\"goods_id\":1},{\"num\":1,\"goods_id\":8}]","grade_id":"3","session_token":"71a517fde038ef03f8a135d8b47d8025"}',true);//json_decode($_POST);
            $goodsList= I('post.goods_info');
            $goodsList=htmlspecialchars_decode($goodsList);
            //$this->ajaxReturn($goodsList);
            //dump($goodsList);die;
            //$this->ajax(200,'succe',$goodsList);
            $goodsList=json_decode($goodsList,true);
            //dump($goodsList);die;
            //LogService::S()->writeLog('error','t',$goodsList);
            if(!$goodsList) {
                $this->ajax(202,'请选择商品');
            }
            $grade_id = I('post.grade_id');
            if($grade_id!=3&&$grade_id!=4) {
                $this->ajax(202,'等级错误');
            }
            if($this->member['grade_id']>=$grade_id) {
                $this->ajax(202,'您无需申请该等级');
            }
            $all=0;
            foreach ($goodsList as $k=>$v){
                $all+=$v['num'];
                $goodsList[$k]['goods_num']=$v['num'];
            }
            if($grade_id==3) {
                if($all!=2) {
                    $this->ajax(202,'请选择2套商品');
                }
            }
            if($grade_id==4) {
                if($all!=5) {
                    $this->ajax(202,'请选择5套商品');
                }
            }
            $result = self::createOrder($goodsList,$grade_id);//$this->_get_order_data($goods_info,$delivery_data,$grade_id);
            if($result){
                $this->ajax(200,'success',$result);
            }else{
                $this->ajax(202,'error');
            }
        }catch (Exception $ex){
            $this->ajax(202,'Exception:'.$ex->getMessage());
        }
    }

    /*
     * 计算要支付商品的钱
     * $type订单类型0升级，1重消 2提货
     */
    protected function _get_pay_money($goods_info){
        //计算商品价格
        //等级价格
        $num = 0;//商品总量
        $money = array();
        foreach ($goods_info as $k=>$v){
            $num += $v['num'];
            $money['money'] += $v['num'] * $v['shop_price'];
        }
        $money['money'] = round($money['money'],2);
        $money['all_money'] = $money['money'];
        return $money;
    }

    /*
    * 获取收货地址信息
    */
    protected function _get_delivery_data(){
        $addressModel = M('address');
        if(!$_POST['address_id']){
            return false;
        }
        $data = $addressModel->where(array('uid'=>$this->uid,'id'=>$_POST['address_id']))->find();
        if(empty($data)){
            return false;
        }
        $data['wechat_user'] = $_POST['wechat_user'];
        $data['idcard'] = $_POST['idcard'];
        return $data;
    }




}